<?php

/*
 * Following code will create a new product row
 * All user details are read from HTTP Post Request
 */

// array for JSON response
$response = array();

// check for required fields
if (isset($_POST['Username']) && isset($_POST['Password']) && isset($_POST['Firstname']) && isset($_POST['Lastname']) && isset($_POST['Email'])) {
    
    $username = $_POST['Username'];
    $password = $_POST['Password'];
    $firstname = $_POST['Firstname'];
    $lastname = $_POST['Lastname'];
    $email = $_POST['Email'];

    // include db connect class
    require_once __DIR__ . '/db_connect.php';

    // connecting to db
    $db = new DB_CONNECT();

    // mysql inserting a new row
    $result = mysql_query("INSERT INTO User(Username, Password, Firstname, Lastname, Email) VALUES('$username', '$password', '$firstname', '$lastname', '$email')");

    // check if row inserted or not
    if ($result) {
        // successfully inserted into database
        $response["success"] = 1;
        $response["message"] = "User successfully created.";

        // echoing JSON response
        echo json_encode($response);
    } else {
	
		$result = mysql_query("SELECT * FROM User WHERE Username = '" .$_POST["Username"] . "'");
		
		if (mysql_num_rows($result) > 0) 
		{
			//User already exists
			$response["success"] = 2;
			$response["message"] = "User already exists.";
		}
		else
		{
			// failed to insert row
			$response["success"] = 0;
			$response["message"] = "Oops! An error occurred.";
		}
        
        // echoing JSON response
        echo json_encode($response);
    }
} else {
    // required field is missing
    $response["success"] = 0;
    $response["message"] = "Required field(s) is missing";

    // echoing JSON response
    echo json_encode($response);
}
?>